package utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.google.common.collect.Lists;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.commons.lang3.tuple.Pair;
import org.springframework.util.CollectionUtils;

/**
 * @Author : orangeCy.奕
 * @Product : 猎豹养成产品源码
 * @Time : 2023/9/2
 * @Desc : CompareUtils
 */
public class CompareUtils {

    /**
     * 单个对象的对比比较,如果不一样返回新老对比
     * @param oldObject
     * @param newObject
     * @param verifyField 比较指定的字段
     * @return
     */
    public static Pair<Boolean,String> compare(Object oldObject, Object newObject, List<String> verifyField) {

        if (oldObject == null && newObject == null) {
            return new ImmutablePair<>(true,"");
        }
        if (oldObject == null || newObject == null) {
            return new ImmutablePair<>(false,"");
        }
        if(CollectionUtils.isEmpty(verifyField)) {
            return new ImmutablePair<>(true,"");
        }
        String oldValueString = JSON.toJSONString(oldObject, SerializerFeature.WriteNullStringAsEmpty);
        String newValueString = JSON.toJSONString(newObject, SerializerFeature.WriteNullStringAsEmpty);
        JSONObject oldJsonObj = JSONObject.parseObject(oldValueString);
        JSONObject newJsonObj = JSONObject.parseObject(newValueString);

        List<Boolean> verifyResList = Lists.newArrayList();

        StringBuilder diff = new StringBuilder().append("[");

        for(int i =0 ;i< verifyField.size() ;i ++) {
            String verifyFiled = verifyField.get(i);
            Object oldVerifyValue = oldJsonObj.get(verifyFiled);
            Object newVerifyValue = newJsonObj.get(verifyFiled);
            if(oldVerifyValue == null && newVerifyValue == null) {
                verifyResList.add(true);
                continue;
            }
            if (oldVerifyValue == null || newVerifyValue == null) {
                diff.append(verifyFiled).append(":{").append("old=").append(oldVerifyValue).append(",new=").append(newVerifyValue).append("},");
                verifyResList.add(false);
                continue;
            }
            boolean verifyRes = StringUtils.equals(oldVerifyValue.toString(), newVerifyValue.toString());
            if(!verifyRes) {
                diff.append(verifyFiled).append(":{").append("old=").append(oldVerifyValue).append(",new=").append(newVerifyValue).append("}");
                if(i < verifyField.size() -1 ) {
                    diff.append(",");
                }
            }
            verifyResList.add(verifyRes);
        }
        return new ImmutablePair<>(verifyResList.stream().allMatch(Boolean.TRUE::equals),diff.append("]").toString());
    }
}